<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>jQuery最佳实践 | 个人博客 | 一个coder的成长记录</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="jQuery">
    <meta name="description" content="jQuery最佳实践 本文介绍一些使用jQuery的通用标准和最佳实践，这些标准不涵盖Javascript的标准和最佳实践，英文原文地址是 http://lab.abhinayrathore.com/jquery-standards/。 中文地址: http://keenwon.com/955.html  加载jQuery1、尽量使用CDN加载： 12&amp;lt;script type=&quot;text/j">
<meta name="keywords" content="jQuery">
<meta property="og:type" content="article">
<meta property="og:title" content="jQuery最佳实践">
<meta property="og:url" content="https://betgar.github.io/2018/04/19/jquery-best-practice/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="jQuery最佳实践 本文介绍一些使用jQuery的通用标准和最佳实践，这些标准不涵盖Javascript的标准和最佳实践，英文原文地址是 http://lab.abhinayrathore.com/jquery-standards/。 中文地址: http://keenwon.com/955.html  加载jQuery1、尽量使用CDN加载： 12&amp;lt;script type=&quot;text/j">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-04-12T09:42:14.470Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="jQuery最佳实践">
<meta name="twitter:description" content="jQuery最佳实践 本文介绍一些使用jQuery的通用标准和最佳实践，这些标准不涵盖Javascript的标准和最佳实践，英文原文地址是 http://lab.abhinayrathore.com/jquery-standards/。 中文地址: http://keenwon.com/955.html  加载jQuery1、尽量使用CDN加载： 12&amp;lt;script type=&quot;text/j">
    
        <link rel="alternate" type="application/atom+xml" title="个人博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide">
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">俊男</h5>
          <a href="mailto:betgar@163.com" title="betgar@163.com" class="mail">betgar@163.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/">
                <i class="icon icon-lg icon-home"></i>
                Home
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives">
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags">
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories">
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/betgar" target="_blank">
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/u/2296734915" target="_blank">
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/about">
                <i class="icon icon-lg icon-link"></i>
                About
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">jQuery最佳实践</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">jQuery最佳实践</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-04-19T12:00:00.000Z" itemprop="datePublished" class="page-time">
  2018-04-19
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/jQuery/">jQuery</a></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#jQuery最佳实践"><span class="post-toc-number">1.</span> <span class="post-toc-text">jQuery最佳实践</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#加载jQuery"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">加载jQuery</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#jQuery变量"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">jQuery变量</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#选择器"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">选择器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#DOM操作"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">DOM操作</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#事件"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">事件</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#AJAX"><span class="post-toc-number">1.6.</span> <span class="post-toc-text">AJAX</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#动画效果"><span class="post-toc-number">1.7.</span> <span class="post-toc-text">动画效果</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#插件"><span class="post-toc-number">1.8.</span> <span class="post-toc-text">插件</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#链式调用"><span class="post-toc-number">1.9.</span> <span class="post-toc-text">链式调用</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#其他"><span class="post-toc-number">1.10.</span> <span class="post-toc-text">其他</span></a></li></ol></li></ol>
        </nav>
    </aside>


<article id="post-jquery-best-practice" class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">jQuery最佳实践</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-04-19 20:00:00" datetime="2018-04-19T12:00:00.000Z" itemprop="datePublished">2018-04-19</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/jQuery/">jQuery</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style="display:none">
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="jQuery最佳实践"><a href="#jQuery最佳实践" class="headerlink" title="jQuery最佳实践"></a>jQuery最佳实践</h1><blockquote>
<p>本文介绍一些使用jQuery的通用标准和最佳实践，这些标准不涵盖Javascript的标准和最佳实践，英文原文地址是 <a href="http://lab.abhinayrathore.com/jquery-standards/" target="_blank" rel="noopener">http://lab.abhinayrathore.com/jquery-standards/</a>。</p>
<p>中文地址: <a href="http://keenwon.com/955.html" target="_blank" rel="noopener">http://keenwon.com/955.html</a></p>
</blockquote>
<h2 id="加载jQuery"><a href="#加载jQuery" class="headerlink" title="加载jQuery"></a>加载jQuery</h2><p>1、尽量使用CDN加载：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="xml">window.jQuery || document.write('<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"js/jquery-1.11.0.min.js"</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="xml"><span class="tag">&lt;<span class="name">\</span>/<span class="attr">script</span>&gt;</span>')</span></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>2、就像上面的代码一样，在CDN加载失败时，要回源到本地服务器的同版本jQuery。</p>
<p>3、使用<a href="http://keenwon.com/577.html" target="_blank" rel="noopener">依赖协议的URL</a>（不加<code>http:</code>和<code>https:</code>，直接使用<code>//</code>），参看上面的例子。</p>
<p>4、尽可能在页面底部加载jQuery和javascript。</p>
<p>5、如何选择jQuery版本？</p>
<ul>
<li>如果要兼容IE6/7/8，不要使用2.x版本的</li>
<li>对于新的应用，如果不考虑一些插件的兼容性问题，尽可能的使用最新版</li>
<li>从CDN加载jQuery的时候，使用完整的版本号（例如，使用1.11.0，不用1.11和1）</li>
<li>不要加载多个版本的jQuery</li>
</ul>
<p>6、如果你使用了Prototype, MooTools, Zepto等，尝试使用<code>jQuery</code>代替<code>$</code>。可以使用<code>$.noConflict()</code>让出<code>$</code>的控制权。</p>
<h2 id="jQuery变量"><a href="#jQuery变量" class="headerlink" title="jQuery变量"></a>jQuery变量</h2><p>1、所有被缓存的jQuery对象，变量名以<code>$</code>开头。</p>
<p>2、总是缓存jQuery选择器返回的对象，方便复用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> $myDiv = $(<span class="string">"#myDiv"</span>);</span><br><span class="line">$myDiv.click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;...&#125;);</span><br></pre></td></tr></table></figure>
<p>3、使用驼峰命名。</p>
<h2 id="选择器"><a href="#选择器" class="headerlink" title="选择器"></a>选择器</h2><p>1、尽可能的使用ID选择器。ID选择器使用<code>document.getElementById()</code>，所以更快。</p>
<p>2、当使用类选择器的时候，不要加DOM元素类型：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> $products = $(<span class="string">"div.products"</span>); <span class="comment">// 慢</span></span><br><span class="line"><span class="keyword">var</span> $products = $(<span class="string">".products"</span>); <span class="comment">// 快</span></span><br></pre></td></tr></table></figure>
<p>3、使用find查找ID-&gt;Child的嵌套查询，<code>.find()</code>方法更快，因为第一次选择没有使用jQuery的选择器引擎：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 差, 全部使用jQuery的选择器引擎</span></span><br><span class="line"><span class="keyword">var</span> $productIds = $(<span class="string">"#products div.id"</span>);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 好, #products使用document.getElementById(), 只有div.id需要使用jQuery的选择器引擎</span></span><br><span class="line"><span class="keyword">var</span> $productIds = $(<span class="string">"#products"</span>).find(<span class="string">"div.id"</span>);</span><br></pre></td></tr></table></figure>
<p>4、越靠右侧越具体：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 差</span></span><br><span class="line">$(<span class="string">"div.data .gonzalez"</span>);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 最佳</span></span><br><span class="line">$(<span class="string">".data td.gonzalez"</span>);</span><br></pre></td></tr></table></figure>
<p>5、选择器不要太“具体”：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">".data table.attendees td.gonzalez"</span>);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 更好，尽可能省去中间部分</span></span><br><span class="line">$(<span class="string">".data td.gonzalez"</span>);</span><br></pre></td></tr></table></figure>
<p>6、给选择器指定上下文（限定范围）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 慢，因为它在整个DOM结构中查找</span></span><br><span class="line">$(<span class="string">'.class'</span>);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 快，因为它只查找 class-container 下的.</span></span><br><span class="line">$(<span class="string">'.class'</span>, <span class="string">'#class-container'</span>);</span><br></pre></td></tr></table></figure>
<p>7、避免使用“*”：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">'div.container &gt; *'</span>); <span class="comment">// 差</span></span><br><span class="line">$(<span class="string">'div.container'</span>).children(); <span class="comment">// 好</span></span><br></pre></td></tr></table></figure>
<p>8、避免隐式使用“*”</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">'div.someclass :radio'</span>); <span class="comment">// 差，还是用了“*”</span></span><br><span class="line">$(<span class="string">'div.someclass input:radio'</span>); <span class="comment">// 好</span></span><br></pre></td></tr></table></figure>
<p>9、不要使用多个ID选择器，或者嵌套使用ID选择器，单独的ID选择器使用<code>document.getElementById()</code>，速度很快：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">'#outer #inner'</span>); <span class="comment">// 差</span></span><br><span class="line">$(<span class="string">'div#inner'</span>); <span class="comment">// 差</span></span><br><span class="line">$(<span class="string">'.outer-container #inner'</span>); <span class="comment">// 差</span></span><br><span class="line">$(<span class="string">'#inner'</span>); <span class="comment">// 好, 调用 document.getElementById()</span></span><br></pre></td></tr></table></figure>
<h2 id="DOM操作"><a href="#DOM操作" class="headerlink" title="DOM操作"></a>DOM操作</h2><p>1、先把元素分离出DOM结构，再进行复杂的操作，之后再附加回DOM中。不明白原因的话，可以了解下<code>.detach()</code>这个方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> $myList = $(<span class="string">"#list-container &gt; ul"</span>).detach();</span><br><span class="line"><span class="comment">// 对 $myList 执行大量复杂操作</span></span><br><span class="line">$myList.appendTo(<span class="string">"#list-container"</span>);</span><br></pre></td></tr></table></figure>
<p>2、使用字符串连接或者array.join()，少用.append()，<a href="http://jsperf.com/jquery-append-vs-string-concat" target="_blank" rel="noopener">点击这里</a>查看性能比较。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 慢</span></span><br><span class="line"><span class="keyword">var</span> $myList = $(<span class="string">"#list"</span>);</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">10000</span>; i++)&#123;</span><br><span class="line">    $myList.append(<span class="string">"&lt;li&gt;"</span>+i+<span class="string">"&lt;/li&gt;"</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 快</span></span><br><span class="line"><span class="keyword">var</span> $myList = $(<span class="string">"#list"</span>);</span><br><span class="line"><span class="keyword">var</span> list = <span class="string">""</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">10000</span>; i++)&#123;</span><br><span class="line">    list += <span class="string">"&lt;li&gt;"</span>+i+<span class="string">"&lt;/li&gt;"</span>;</span><br><span class="line">&#125;</span><br><span class="line">$myList.html(list);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 更快</span></span><br><span class="line"><span class="keyword">var</span> array = []; </span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">10000</span>; i++)&#123;</span><br><span class="line">    array[i] = <span class="string">"&lt;li&gt;"</span>+i+<span class="string">"&lt;/li&gt;"</span>; </span><br><span class="line">&#125;</span><br><span class="line">$myList.html(array.join(<span class="string">''</span>));</span><br></pre></td></tr></table></figure>
<p>3、不要对不存在的元素做操作：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 差: 在发现该ID不存在之前，已经执行了3个函数</span></span><br><span class="line">$(<span class="string">"#nosuchthing"</span>).slideUp();</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 好</span></span><br><span class="line"><span class="keyword">var</span> $mySelection = $(<span class="string">"#nosuchthing"</span>);</span><br><span class="line"><span class="keyword">if</span> ($mySelection.length) &#123;</span><br><span class="line">    $mySelection.slideUp();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h2><p>1、一个页面只使用一个Document ready，便于调试和跟踪。</p>
<p>2、不要使用匿名函数绑定事件，匿名函数不利于调试，复用，测试，debug：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myLink"</span>).on(<span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;...&#125;); <span class="comment">// 差 </span></span><br><span class="line"><span class="comment">// 好</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">myLinkClickHandler</span>(<span class="params"></span>)</span>&#123;...&#125;$(<span class="string">"#myLink"</span>).on(<span class="string">"click"</span>, myLinkClickHandler);</span><br></pre></td></tr></table></figure>
<p>3、Document ready 不要用匿名函数，原因同上：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; ... &#125;); <span class="comment">// 差: 你没办法写单元测试和复用</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">// 好</span></span><br><span class="line">$(initPage); <span class="comment">// or $(document).ready(initPage);</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initPage</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>4、Document ready 的处理函数应该写在外部文件，内联的javascript可以在一些初始化设置之后调用 ready 函数，例如：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"my-document-ready.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">	<span class="comment">// 做一些初始化设置.</span></span></span><br><span class="line"><span class="javascript">	$(<span class="built_in">document</span>).ready(initPage); <span class="comment">// or $(initPage); initPage函数在外部文件中</span></span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>5、不要把事件直接写在HTML元素上，这样不方便调试：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">id</span>=<span class="string">"myLink"</span> <span class="attr">href</span>=<span class="string">"#"</span> <span class="attr">onclick</span>=<span class="string">"myEventHandler();"</span>&gt;</span>my link<span class="tag">&lt;/<span class="name">a</span>&gt;</span> <span class="comment">&lt;!-- 差--&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myLink"</span>).on(<span class="string">"click"</span>, myEventHandler); <span class="comment">// 好</span></span><br></pre></td></tr></table></figure>
<p>6、尽可能的给事件加上命名空间。这样方便解除绑定，而不影响该DOM元素的其他事件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myLink"</span>).on(<span class="string">"click.mySpecialClick"</span>, myEventHandler); <span class="comment">// 好</span></span><br><span class="line"><span class="comment">// 之后，很容易的解除绑定</span></span><br><span class="line">$(<span class="string">"#myLink"</span>).unbind(<span class="string">"click.mySpecialClick"</span>);</span><br></pre></td></tr></table></figure>
<h2 id="AJAX"><a href="#AJAX" class="headerlink" title="AJAX"></a>AJAX</h2><p>1、使用<code>.ajax()</code>，避免<code>.getJson()</code>或者<code>.get()</code>，它们在内部也是调用<code>.ajax()</code>的。</p>
<p>2、不要在<code>https</code>的站点上请求<code>http</code>，使用<a href="http://keenwon.com/577.html" target="_blank" rel="noopener">依赖协议的URL</a></p>
<p>3、不要把数据加在url上，使用data属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可读性差</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    url: <span class="string">"something.php?param1=test1&amp;param2=test2"</span>,</span><br><span class="line">    ....</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 可读性好</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    url: <span class="string">"something.php"</span>,</span><br><span class="line">    data: &#123; <span class="attr">param1</span>: test1, <span class="attr">param2</span>: test2 &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>4、指定dataType属性，更容易知道数据类型。</p>
<p>5、对于ajax加载的内容，使用委托绑定事件，这样可以在元素不存在的时候执行绑定。（之后ajax加载进DOM结构中）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#parent-container"</span>).on(<span class="string">"click"</span>, <span class="string">"a"</span>, delegatedClickHandlerForAjax);</span><br></pre></td></tr></table></figure>
<p>6、使用Promise</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123; ... &#125;).then(successHandler, failureHandler);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="keyword">var</span> jqxhr = $.ajax(&#123; ... &#125;);</span><br><span class="line">jqxhr.done(successHandler);</span><br><span class="line">jqxhr.fail(failureHandler);</span><br></pre></td></tr></table></figure>
<p>7、抽象出ajax模板，方便复用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> jqxhr = $.ajax(&#123;</span><br><span class="line">    url: url,</span><br><span class="line">    type: <span class="string">"GET"</span>, <span class="comment">// default is GET but you can use other verbs based on your needs.</span></span><br><span class="line">    cache: <span class="literal">true</span>, <span class="comment">// default is true, but false for dataType 'script' and 'jsonp', so set it on need basis.</span></span><br><span class="line">    data: &#123;&#125;, <span class="comment">// add your request parameters in the data object.</span></span><br><span class="line">    dataType: <span class="string">"json"</span>, <span class="comment">// specify the dataType for future reference</span></span><br><span class="line">    jsonp: <span class="string">"callback"</span>, <span class="comment">// only specify this to match the name of callback parameter your API is expecting for JSONP requests.</span></span><br><span class="line">    statusCode: &#123; <span class="comment">// if you want to handle specific error codes, use the status code mapping settings.</span></span><br><span class="line">        <span class="number">404</span>: handler404,</span><br><span class="line">        <span class="number">500</span>: handler500</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">jqxhr.done(successHandler);</span><br><span class="line">jqxhr.fail(failureHandler);</span><br></pre></td></tr></table></figure>
<h2 id="动画效果"><a href="#动画效果" class="headerlink" title="动画效果"></a>动画效果</h2><p>1、Adopt a restrained and consistent approach to implementing animation functionality（大意：采取受限制的和统一的方法来实现动画功能。）</p>
<p>2、满足用户体验即可，不要做过多的动画：</p>
<ul>
<li>尽量使用简单的show/hide，slideUp/slideDown来切换元素</li>
<li>尽量使用jQuery预定义的时间间隔（durations），“slow”，“fast”或者400（中等）</li>
</ul>
<h2 id="插件"><a href="#插件" class="headerlink" title="插件"></a>插件</h2><p>1、选择兼容性好，文档，测试齐全何社区支持好的插件。</p>
<p>2、检查插件在不同版本jQuery下的兼容性。</p>
<p>3、任何参加的可复用的组件，都应该以插件的形式实现。</p>
<h2 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h2><p>1、使用链式调用代替变量缓存和多次调用选择器：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myDiv"</span>).addClass(<span class="string">"error"</span>).show();</span><br></pre></td></tr></table></figure>
<p>2、当链式调用超过3级的时候，适当的换行增加可读性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myLink"</span>)</span><br><span class="line">    .addClass(<span class="string">"bold"</span>)</span><br><span class="line">    .on(<span class="string">"click"</span>, myClickHandler)</span><br><span class="line">    .on(<span class="string">"mouseover"</span>, myMouseOverHandler)</span><br><span class="line">    .show();</span><br></pre></td></tr></table></figure>
<p>3、链太长的时候，缓存中间对象是可以接受的。</p>
<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>1、参数尽量使用对象形式：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$myLink.attr(<span class="string">"href"</span>, <span class="string">"#"</span>).attr(<span class="string">"title"</span>, <span class="string">"my link"</span>).attr(<span class="string">"rel"</span>, <span class="string">"external"</span>); <span class="comment">// 差, 调用三次attr()</span></span><br><span class="line"><span class="comment">// 好, 调用一次</span></span><br><span class="line">$myLink.attr(&#123;</span><br><span class="line">    href: <span class="string">"#"</span>,</span><br><span class="line">    title: <span class="string">"my link"</span>,</span><br><span class="line">    rel: <span class="string">"external"</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>2、尽量不要把css混在js中：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.error</span> &#123; <span class="attribute">color</span>: red; <span class="attribute">font-weight</span>: bold; &#125; <span class="comment">/* 好*/</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#mydiv"</span>).css(&#123;<span class="string">'color'</span>:red, <span class="string">'font-weight'</span>:<span class="string">'bold'</span>&#125;); <span class="comment">// 差</span></span><br><span class="line">$(<span class="string">"#mydiv"</span>).addClass(<span class="string">"error"</span>); <span class="comment">// 好</span></span><br></pre></td></tr></table></figure>
<p>3、不要使用过时的方法，注意新版更新时弃用的方法，不要使用它们。</p>
<p>4、必要的时候使用原生js，这里看查看性能对比 <a href="http://jsperf.com/document-getelementbyid-vs-jquery/3" target="_blank" rel="noopener">http://jsperf.com/document-getelementbyid-vs-jquery/3</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#myId"</span>); <span class="comment">// 还是有一点点点点慢...</span></span><br><span class="line"><span class="built_in">document</span>.getElementById(<span class="string">"myId"</span>);</span><br></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-04-12T09:42:14.470Z" itemprop="dateUpdated">2019-04-12 17:42:14</time>
</span><br>


        
        原文链接：<a href="/2018/04/19/jquery-best-practice/" target="_blank" rel="external">https://betgar.github.io/2018/04/19/jquery-best-practice/</a>
        
    </div>
    
    <footer>
        <a href="https://betgar.github.io">
            <img src="/img/avatar.jpg" alt="俊男">
            俊男
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/jQuery/">jQuery</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://betgar.github.io/2018/04/19/jquery-best-practice/&title=《jQuery最佳实践》 — 个人博客&pic=https://betgar.github.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://betgar.github.io/2018/04/19/jquery-best-practice/&title=《jQuery最佳实践》 — 个人博客&source=各种技术加身的coder" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://betgar.github.io/2018/04/19/jquery-best-practice/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《jQuery最佳实践》 — 个人博客&url=https://betgar.github.io/2018/04/19/jquery-best-practice/&via=https://betgar.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://betgar.github.io/2018/04/19/jquery-best-practice/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/06/01/node-env-config/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Node环境配置</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/04/17/qem-manual/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">qem-manual(使用手册)</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "kiGWA9mdoVtQlfGYA5uDBNX7-gzGzoHsz",
            appKey: "dHCOdD0oEIjJd0cJoAHHN0y3",
            avatar: "mm",
            placeholder: "Just comment it",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style="display:none">
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style="display:none">
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>俊男 &copy; 2017 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://betgar.github.io/2018/04/19/jquery-best-practice/&title=《jQuery最佳实践》 — 个人博客&pic=https://betgar.github.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://betgar.github.io/2018/04/19/jquery-best-practice/&title=《jQuery最佳实践》 — 个人博客&source=各种技术加身的coder" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://betgar.github.io/2018/04/19/jquery-best-practice/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《jQuery最佳实践》 — 个人博客&url=https://betgar.github.io/2018/04/19/jquery-best-practice/&via=https://betgar.github.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://betgar.github.io/2018/04/19/jquery-best-practice/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
